package com.gk.panda.apis.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gk.panda.apis.Vo.exports.ExportLogVO;
import com.gk.panda.apis.dto.OperationLogDto;
import com.gk.panda.apis.mapper.LogMapper;
import com.gk.panda.apis.service.LogService;
import com.gk.panda.apis.util.ListCopyUtils;
import com.gk.panda.apis.util.excel.ExcelUtils;
import com.gk.panda.pojo.OperationLog;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Service
public class LogServiceImpl extends ServiceImpl<LogMapper, OperationLog> implements LogService {

    private static final String FILE_SUFFIX = ".xlsx";

    /**
     * 分页查询操作日志
     * @param dto
     * @return
     */
    @Override
    public Page<OperationLog> listOperationLog(OperationLogDto dto) {
        Page<OperationLog> page = new Page<>(dto.getPageNumber(), dto.getPageSize());
        QueryWrapper<OperationLog> wrapper = new QueryWrapper<>();
        if (dto.getSearchParam() != null && !dto.getSearchParam().equals("")) {
            wrapper.and(queryWrapper -> {
                queryWrapper.like("operator",dto.getSearchParam())
                        .or().like("operation",dto.getSearchParam());
            });
        }
        wrapper.gt(dto.getStartTime() != null,"operation_time",dto.getStartTime());
        wrapper.lt(dto.getEndTime() != null,"operation_time",dto.getEndTime());
        wrapper.orderByDesc("operation_time");
        return this.page(page,wrapper);
    }

    /**
     * 导出操作日志
     * @param response
     */
    @Override
    public void export(HttpServletResponse response) {
        List<OperationLog> logs = list();
        List<ExportLogVO> vos = ListCopyUtils.copyListProperties(logs, ExportLogVO::new);
        // 导出
        ExportParams params = new ExportParams();
        params.setSheetName("操作日志");
        params.setHeight((short) 15);
        Workbook workbook = ExcelExportUtil.exportBigExcel(params, ExportLogVO.class, vos);
        ExcelExportUtil.closeExportBigExcel();
        // 生成文件
        String downloadFileName = "操作日志导出" + FILE_SUFFIX;
        ExcelUtils.download(downloadFileName, workbook, response);
    }
}
